package com.codyy.felix.webconsole.plugins.route.rest;

import com.codyy.felix.webconsole.plugins.route.core.RouteService;
import com.codyy.felix.webconsole.plugins.route.core.pojo.RouteParams;
import com.codyy.felix.webconsole.plugins.route.core.pojo.RouteProgress;
import com.codyy.felix.webconsole.plugins.route.core.provider.OsgiExplorer;
import com.codyy.felix.webconsole.plugins.route.exception.RouteException;
import com.codyy.felix.webconsole.plugins.route.utils.JsonUtils;
import com.codyy.felix.webconsole.plugins.route.utils.RouteUtil;
import com.google.common.collect.Lists;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.webconsole.AbstractWebConsolePlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.codyy.felix.webconsole.plugins.route.utils.JsonUtils.MessageType;
import static com.codyy.felix.webconsole.plugins.route.utils.JsonUtils.writeMessage;

public class ByPhraseServlet extends RestServlet {

	private static final String ALIAS_NAME = "by-phrase";

	private static final String FIELD_BUNDLEFILE = "routeFile";

	private static final String ACTION_INSTALL = "install";
	private static final String ACTION_UPDATE = "update";
	private final RouteService route;
	private final OsgiExplorer osgiExplorer;
	public ByPhraseServlet(BundleContext bundleContext) {
		super(bundleContext);
		this.route = new RouteService(bundleContext);
		this.osgiExplorer = new OsgiExplorer(bundleContext);
	}

	@Override
	protected String getAliasName() {
		return ALIAS_NAME;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

		final String action = RouteUtil.getParameter( request, "action" );

		final Map params = ( Map ) request.getAttribute( AbstractWebConsolePlugin.ATTR_FILEUPLOAD );
		if ( params == null ) {
			writeMessage(response, MessageType.ERROR, "获取文件内容失败.");
			return;
		}

		final FileItem[] bundleItems = getFileItem( params, FIELD_BUNDLEFILE );
		if (bundleItems == null || bundleItems.length <= 0)  {
			writeMessage(response, MessageType.ERROR, "文件未上传.");
			return;
		}
		FileItem fileItem = bundleItems[0];
		if (ACTION_INSTALL.equals(action)) {
			String errorMsg = route.validRouteFile(fileItem, bundleContext.getBundles());
			if (StringUtils.isNotBlank(errorMsg)) {
				JsonUtils.writeHtml(response,
						"<script type='text/javascript'>alert('"+ errorMsg + "！');window.history.back(-1);</script></body>");
				return;
			}
			try {
				route.coptyToDeploy(fileItem, osgiExplorer.findXmlPath());

			} catch (Exception e) {
				JsonUtils.writeHtml(response,
						"<script type='text/javascript'>alert('文件拷贝到目标目录失败："+ e.getMessage() + "！');window.history.back(-1);</script></body>");
				return;
			}
			JsonUtils.writeHtml(response,
					"<script type='text/javascript'>alert('保存成功！');window.history.back(-1);</script></body>");
		} else if (ACTION_UPDATE.equals(action)) {
			System.out.println(">>>>>bundle:id " + RouteUtil.getParameter(request, "bundleId"));

			Bundle  targetBundle = Optional.ofNullable(RouteUtil.getParameter(request, "bundleId"))
					.map(osgiExplorer::findBundle).orElse(null);
			try {
				route.updateFile(fileItem, targetBundle);

				JsonUtils.writeHtml(response,
						"<script type='text/javascript'>alert('更新成功！');window.history.back(-1);</script></body>");

			} catch (RouteException re) {
				JsonUtils.writeHtml(response,
						"<script type='text/javascript'>alert('" + re.getMessage() + "');window.history.back(-1);</script></body>");
			}

		} else {
			JsonUtils.writeHtml(response,
					"<script type='text/javascript'>alert('错误：未指定操作！');window.history.back(-1);</script></body>");
		}
	}


	private FileItem[] getFileItem(Map params, String name ) {
		return (FileItem[])params.get(name);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  IOException {

		String phrase = getPhrase(request);

		final List<String> providers = getProviders(request);

		Bundle[] bundles = bundleContext.getBundles();
		final RouteParams params = new RouteParams(phrase, providers, getResultLimit(request), getCached(request));
		final RouteProgress progress = route.search(params, bundles);

		personalizeResult(response, params);
		writeMessage(response, MessageType.SUCCESS, "Results found", progress);
	}


	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Bundle bundle = Optional.ofNullable(req.getParameter("bundleId"))
				.map(osgiExplorer::findBundle).orElse(null);
		try {
			route.deleteRouteFile(bundle);
		} catch (BundleException | RouteException e) {
			writeMessage(resp, MessageType.SUCCESS, "删除失败，" + e.getMessage());
		}
		writeMessage(resp, MessageType.SUCCESS, "删除成功.");
	}


	private void personalizeResult(HttpServletResponse response, RouteParams params) {
		response.setHeader("Content-Disposition", String.format("attachment; filename='route_%s.json'", params.getPhrase()));
	}

	@Override
	public void destroy() {
		route.dispose();

		super.destroy();
	}
}
